package cn.edu.anan.controller;

import cn.edu.anan.rule.MySentinelResource;
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.EntryType;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * sentinel demo controller
 * </p>
 *
 * @author yanghouhua@foresee.com.cn
 * @since 2021/8/5
 */
@RestController
@RequestMapping("sentinel")
@Slf4j
public class SentinelController {

    /**
     * 测试流控
     * @param userId
     * @return
     */
    @RequestMapping("flow")
    public String flow(String userId){
        Entry entry = null;
        String result = "flow,ok!";
        try{
            // 1.开始进入资源，流控保护开始
            SphU.entry(MySentinelResource.FLOW_RESOURCE);

            // 2.被保护的资源
            log.info("SentinelController--flow，param：{}", userId);

        }catch (BlockException e){
            log.error("发生流控异常! msg：{}", e);
            result = "error!限流了!";
        }finally {
            // 3.释放资源，需要与SphU.entry配对
            if(entry != null){
                entry.exit();
            }
        }

       return result;
    }

    /**
     * 测试熔断降级规则
     * @return
     */
    @RequestMapping("degrade")
    @SentinelResource(value =MySentinelResource.DEGRADE_RESOURCE, fallback = "degradeFallback")
    public String degrade(){
        log.info("SentinelController--annotationDegrade start");
        int time = new Random().nextInt(1000);
        try {
            TimeUnit.MILLISECONDS.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("SentinelController--annotationDegrade end，耗时：{}毫秒",time);
        return "degrade ok!";
    }


    public String degradeFallback(Throwable e){
        log.error("熔断降级了，异常消息：{}", e);
        return "error!熔断降级了!";
    }

}
